//
//  WmcClassifyAlbumDetailVM.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/5/18.
//

import UIKit

class WmcClassifyAlbumDetailVM: WmcBaseVM {
    // Lifecycle

    required init() {
        super.init()
        self.pageSize = 20
    }

    // Internal

    enum DataType {
        /// 全部照片
        case allPhoto
        /// 水印照片
        case watermarkPhoto
    }

    /// 刷新数据
    var dataNeedUpdate: (() -> Void)?

    /// 水印类型请求参数
    var watermarkId: Int?

    /// 页面数据类型
    var type: DataType = .allPhoto

    /// 界面显示的列表数据
    private(set) var dataSource: [WmcMediaPhotoGroupModel] = []
    /// 预览页面数据
    private(set) var browserDataSource: [WmcMedia] = []
    /// 是否没有数据
    private(set) var hasNoMore: Bool = false

    /// 获取分享数据的接口
    func fetchShare(completion: @escaping (WmcMediaShareModel) -> Void, failure: @escaping (Error?) -> Void) {
        var ids: [Int] = []
        if let watermarkId = watermarkId {
            ids.append(watermarkId)
        }
        WmcMediaAlbumAPI.fetchAlbumShareInfo(wmIds: ids).subscribe(onNext: { model in
            completion(model)
        }, onError: { error in
            failure(error)
        }).disposed(by: rx.disposeBag)
    }

    /// 刷新列表
    func refresh(completion: @escaping ([WmcMediaPhotoModel]) -> Void, failure: @escaping (Error) -> Void) {
        fetchPhotoList(pageIndex: 1, pageSize: pageSize) { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.page = 2
            weakSelf.hasNoMore = list.count < weakSelf.pageSize
            weakSelf.originalDataSource = list
            weakSelf.dataSource = weakSelf.sortDataList(array: list)
            var temp: [WmcMedia] = []
            weakSelf.originalDataSource.forEach { model in
                if model.resourceType == 0 {
                    temp.append(WmcImage(url: model.url))
                } else if model.resourceType == 1 {
                    temp.append(WmcVideo(url: model.url))
                }
            }
            weakSelf.browserDataSource = temp
            completion(list)
        } failure: { error in
            failure(error)
        }
    }

    /// 加载更多
    func loadMore(completion: @escaping () -> Void, failure: @escaping (Error) -> Void) {
        fetchPhotoList(pageIndex: page, pageSize: pageSize) { [weak self] list in
            guard let weakSelf = self else { return }

            weakSelf.page += 1
            weakSelf.hasNoMore = list.count < weakSelf.pageSize
            weakSelf.originalDataSource.append(contentsOf: list)
            weakSelf.dataSource = weakSelf.sortDataList(array: weakSelf.originalDataSource)
            var temp: [WmcMedia] = []
            weakSelf.originalDataSource.forEach { model in
                if model.resourceType == 0 {
                    temp.append(WmcImage(url: model.url))
                } else if model.resourceType == 1 {
                    temp.append(WmcVideo(url: model.url))
                }
            }
            weakSelf.browserDataSource = temp
            completion()
        } failure: { error in
            failure(error)
        }
    }

    /// 删除照片
    func deleteImage(indexPath: IndexPath, index: Int, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
        if indexPath.section < dataSource.count, index < browserDataSource.count {
            var list = dataSource[indexPath.section].list
            if indexPath.row < list.count {
                let model = list[indexPath.row]
                
                WmcMediaAlbumAPI.deletePhoto(id: model.id).subscribe(onNext: { [weak self] r in
                    guard let weakSelf = self else { return }
                    list.remove(at: indexPath.row)
                    if list.isEmpty {
                        weakSelf.dataSource.remove(at: indexPath.section)
                    } else {
                        let section = weakSelf.dataSource[indexPath.section]
                        section.list = list
                        weakSelf.dataSource[indexPath.section] = section
                    }

                    weakSelf.originalDataSource.remove(at: index)
                    weakSelf.browserDataSource.remove(at: index)
                    weakSelf.dataNeedUpdate?()
                    success()
                }, onError: { error in
                    failure(error)
                }).disposed(by: rx.disposeBag)
            }
        }
    }
    
    func fetchVideoShare(index: Int, success: @escaping (WmcMediaShareModel) -> Void, failure: @escaping (Error?) -> Void) {
        if index < originalDataSource.count {
            let model = originalDataSource[index]
            WmcMediaAlbumAPI.fetchVideoShareInfo(id: model.id).subscribe(onNext: { r in
                success(r)
            }, onError: { error in
                failure(error)
            }).disposed(by: rx.disposeBag)
        } else {
            failure(nil)
        }
    }

    // Private

    /// 接口返回的原始数据
    private var originalDataSource: [WmcMediaPhotoModel] = []

    private func fetchPhotoList(pageIndex: Int, pageSize: Int, completion: @escaping ([WmcMediaPhotoModel]) -> Void, failure: @escaping (Error) -> Void) {
         
        var wmIds: [Int]?
        if let watermarkId = watermarkId {
            wmIds = [watermarkId]
        }
        
        WmcMediaAlbumAPI.fetchPhotoList(page: pageIndex, pageSize: pageSize, wmIds: wmIds).subscribe(onNext: { list in
            completion(list)
        }, onError: { error in
            failure(error)
        }).disposed(by: rx.disposeBag)
    }

    private func sortDataList(array: [WmcMediaPhotoModel]) -> [WmcMediaPhotoGroupModel] {
        let temp: [WmcMediaPhotoModel] = array.map { model in
            let modelTemp = model
            let timeFields = model.takeTime.components(separatedBy: " ")
            if timeFields.count == 2 {
                var takeDateStr = timeFields[0]
                let fields1 = timeFields[0].components(separatedBy: "-")
                if fields1.count == 3 {
                    takeDateStr = "\(fields1[0])年\(fields1[1])月\(fields1[2])日"
                }
                modelTemp.takeTimeDateStr = takeDateStr
                
                var takeTimeStr = timeFields[1]
                let fields = timeFields[1].components(separatedBy: ":")
                if fields.count == 3 {
                    takeTimeStr = "\(fields[0]):\(fields[1])"
                }
                modelTemp.takeTimeStr = takeTimeStr
            }
            return modelTemp
        }

        var groups: [WmcMediaPhotoGroupModel] = []
        temp.forEach { model in
            let dateIndex = groups.firstIndex { modelTemp in
                modelTemp.date == model.takeTimeDateStr
            }

            if dateIndex == nil {
                let group = WmcMediaPhotoGroupModel()
                group.date = model.takeTimeDateStr
                groups.append(group)
            }
        }

        var result: [WmcMediaPhotoGroupModel] = []
        groups.forEach { group in
            let groupTemp = group
            groupTemp.list = []

            var indexs: [Int] = []
            for (index, item) in temp.enumerated() {
                if item.takeTimeDateStr == group.date {
                    groupTemp.list.append(item)
                    indexs.append(index)
                }
            }

            result.append(groupTemp)
        }

        return result
    }
}
